const { app,BrowserWindow,ipcMain,screen,dialog, BrowserWindowProxy} = require('electron');
//窗体关系
let windowsOpen = new Array();
//当前主进程
let win=null;
//更新状态
const updateStateText={
  DOWNLOADING:'正在下载',
  UPDATEWILL:'准备更新',
  NORMAL:'无需更新'
}
let updateState=updateStateText.NORMAL;


//----------------创建窗口开始---------------------------
function createWindow () {   
  let size = screen.getPrimaryDisplay().workAreaSize;
  win = new BrowserWindow({
    width:size.width,
    height:size.height,
    skipTaskbar:false,
    autoHideMenuBar : true,
    show: false,
    icon : "images/spa.png",
    webPreferences: {
      nodeIntegration: true,
      nodeIntegrationInWorker: false,
      enableRemoteModule:true
    }
  })
  win.maximize();
  win.loadFile('./html/login/login.html');
  win.show();
  //主进程窗体大小改变
  win.on('resize',(e)=>{
    if(updateState!=updateStateText.NORMAL)
      return;
    win.reload();
  });
  
  //关闭除了主窗体的其余窗体
  ipcMain.on('coloseWins', (e, arg)=>{
    let needCloseWindows=getOpenWindowsByParent(win.id);
      for(let i=0;i<needCloseWindows.length;i++){
        BrowserWindow.fromId(needCloseWindows[i]).close();
      }
  });
  
  //关闭主进程
  win.on('close',(e)=>{
      if(updateState==updateStateText.UPDATEWILL)
        return;
      e.preventDefault();
      dialog.showMessageBox(win, {
          type: 'warning',
          title: '关闭',
          message: '是否退出？',
          buttons: ['取消', '确定']
      }).then((index) => {
          if (index.response === 1) {
              win = null;
              app.exit();
          }
      });
  })

  //主进程关闭
  win.on('closed',(e)=>{
    app.quit();
  });

  //主进程最小化
  win.on('minimize',()=>{
    let allWindows=BrowserWindow.getAllWindows();
    for(let i=0;i<allWindows.length;i++){
      allWindows[i].minimize();
    }
  });
  win.show();

  //窗体崩溃处理
  breakdown(win);

  //配置更新
  updateHandle();
  
  //打开新窗口
  ipcMain.on('newWindow',(e,url,params={},options={})=>{
    let isOpen=isOpenWindow(url+options.hash);
    if(isOpen!=''){
      let openWindow=BrowserWindow.fromId(isOpen);
      openWindow.show();
      return;
    }
    let y=win.isFullScreen()?win.getPosition()[1]+params.top+10:win.getPosition()[1]+params.top+40;
    newWin = new BrowserWindow({
      title:params.title,
      width: win.getSize()[0], 
      height: win.getSize()[1]-params.top-50,
      x:win.getPosition()[0]+params.left,
      y:y,
      autoHideMenuBar : true,
      modal:false,
      center:true,
      parent:win,
      skipTaskbar:false,
      icon : "images/spa.png",
      webPreferences: {
        nodeIntegration: true,
        nodeIntegrationInWorker: false,
        enableRemoteModule:true
      }
    })
    windowsOpen.push({'uuid':newWin.id,'url':url+options.hash,'parentId':params.parentId});
    newWin.loadFile(url,options);
    newWin.webContents.on('did-finish-load', function(){
      newWin.webContents.send('dataJsonPort', params);
      let windowOpenParams={'oper':'newWindow','title':params.title,'menuCode':params.menuCode,'parentMenuCode':params.parentMenuCode};
      win.webContents.send('windowOper',windowOpenParams);
    });
    let winId=newWin.id;

    newWin.on('close',()=>{
      let windowOpenParams={'oper':'closeWindow','title':params.title,'menuCode':params.menuCode,'parentMenuCode':params.parentMenuCode};
      win.webContents.send('windowOper',windowOpenParams);
    });

    newWin.on('closed',()=>{
      newWin=null;
      let needCloseWindows=getOpenWindowsByParent(winId);
      for(let i=0;i<needCloseWindows.length;i++){
        BrowserWindow.fromId(needCloseWindows[i]).close();
        closeOpenWindow(needCloseWindows[i]);
      }
      closeOpenWindow(winId);
    });
    
    //窗口还原
    newWin.on('restore',()=>{
      let needreStoreWindows=getOpenWindowsByChild(winId);
      for(let i=0;i<needreStoreWindows.length;i++){
        BrowserWindow.fromId(needreStoreWindows[i]).restore();
      }
    });

    //窗体崩溃处理
    breakdown(newWin);
  });

  //打开新模态
  ipcMain.on('newModal',(e,hash,params={},frame=true)=>{
    let parentId=params.parentId;
    newModal = new BrowserWindow({
      title:params.title,
      width: params.hasOwnProperty("width")?params.width:800,
      height: params.hasOwnProperty("height")?params.height:600,
      modal:true,
      center:true,
      frame:frame,
      autoHideMenuBar : true,
      parent:BrowserWindow.fromId(parentId),
      webPreferences: {
        nodeIntegration: true,
        nodeIntegrationInWorker: false,
        enableRemoteModule:true
      }
    });
    newModal.loadFile('./spaindexWindow.html',hash);
    newModal.webContents.on('did-finish-load', function(){
      newModal.webContents.send('dataJsonPort', params);
    });
    newModal.on('closed', () => {
      newModal = null
    })

    //模态还原
    newModal.on('restore',()=>{
      let winId=newModal.getParentWindow().id;
      let needreStoreWindows=getOpenWindowsByChild(winId);
      for(let i=0;i<needreStoreWindows.length;i++){
        BrowserWindow.fromId(needreStoreWindows[i]).restore();
      }
    });

    //窗体崩溃处理
    breakdown(newModal);
  });
}
//----------------创建窗口结束---------------------------

//----------------对窗口的逻辑开始-----------------------
//是否已打开过窗口
function isOpenWindow(v){
  let isOpenValue='';
  for(let i=0;i<windowsOpen.length;i++){
    let item=windowsOpen[i];
    if(item.url==v){
      isOpenValue=item.uuid;
      break;
    }
  }
  return isOpenValue;
}
//关闭窗口
function closeOpenWindow(v){
  let nowOpenWindow=new Array();
  for(let i=0;i<windowsOpen.length;i++){
    let item=windowsOpen[i];
    if(item.uuid!=v){
      nowOpenWindow.push(item);
    }
  }
  windowsOpen=nowOpenWindow;
}
//当前窗口所有关联子孙
function getOpenWindowsByParent(id,result=[]){
    for(let i=0;i< windowsOpen.length;i++){
      let item=windowsOpen[i];
      if(item.parentId==id){
        result.push(item.uuid);
        getOpenWindowsByParent(item.uuid,result);
      }
    }
    return result;
}

//当前窗口所有祖先
function getOpenWindowsByChild(id,result=[]){
  for(let i=0;i< windowsOpen.length;i++){
    let item=windowsOpen[i];
    if(item.uuid==id){
      result.push(item.parentId);
      getOpenWindowsByChild(item.parentId,result);
    }
  }
  return result;
}

//窗体崩溃处理
function breakdown(_win){
  _win.webContents.on('crashed', function () {
    dialog.showMessageBox(_win, {
      type: 'warning',
      title: '关闭',
      message: '是否退出？',
      buttons: ['重载', '关闭']
    }).then((index) => {
      if (index.response === 0) {
        _win.reload();
      }else 
        _win.close();
    });
  });
}
//----------------对窗口的逻辑结束-----------------------

//-----------控制应用程序的事件生命周期-------------------
app.whenReady().then(createWindow)
app.on('window-all-closed', () => {
    app.quit()
})
app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow()
  }
})
//-----------控制应用程序的事件生命周期-------------------

//------------------配置更新----------------------------
const { autoUpdater} = require('electron-updater');
//配置更新
function updateHandle() {
  autoUpdater.setFeedURL('http://hi-thinking.gicp.net:18080/spaUpdate/');
  autoUpdater.autoDownload = false;
  //检查更新出错
  autoUpdater.on('error', function (error) {
    sendUpdateMessage('-1',error)
  });
  //正在检查更新
  autoUpdater.on('checking-for-update', function () {
    sendUpdateMessage('正在检查更新')
  });
  //有更新
  autoUpdater.on('update-available', function (info) {
    sendUpdateMessage('1',info)
  });
  //无需更新
  autoUpdater.on('update-not-available', function (info) {
    sendUpdateMessage('无需更新')
  });
  //下载
  ipcMain.on('downloadUpdate', (e, arg)=>{
    if(arg==0)
      updateState=updateStateText.DOWNLOADING;
    autoUpdater.downloadUpdate();
  });
  //下载进度
  autoUpdater.on('download-progress', function (progressObj) {
    win.webContents.send('downloadProgress', progressObj)
  })
  //下载完成
  autoUpdater.on('update-downloaded', function (event, releaseNotes, releaseName, releaseDate, updateUrl, quitAndUpdate) {
    ipcMain.on('isUpdateNow', (e, arg)=>{
      //执行更新
      updateState=updateStateText.UPDATEWILL;
      autoUpdater.quitAndInstall();
    });
    win.webContents.send('isUpdateNow')
  });
  ipcMain.on("checkForUpdate",()=>{
      autoUpdater.checkForUpdates();
  })
}
//返回更新信息
function sendUpdateMessage(text,info={}) {
  win.webContents.send('message', text,info)
}
//------------------配置更新结束--------------------------
